package com.kai.filter;

import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

public class LoginFilter implements Filter {
    private List excludedUrls;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String excludePattern = filterConfig.getInitParameter("excludedUrls");
        excludedUrls = Arrays.asList(excludePattern.split(","));
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        String path = ((HttpServletRequest) servletRequest).getServletPath();
        if(!excludedUrls.contains(path))
        {
            String token = ((HttpServletRequest) servletRequest).getHeader("token");
            String tokenSession = (String) ((HttpServletRequest) servletRequest).getSession().getAttribute("token");
            if (!token.isEmpty()&&!tokenSession.isEmpty()){
                if (tokenSession.equals(token)){
                    filterChain.doFilter(servletRequest,servletResponse);
                }else{
                    servletResponse.getWriter().println(false);
                    return;
                }
            }else {
                servletResponse.getWriter().println(false);
                return;
            }
        }
        // Forward the request to the next filter or servlet in the chain.
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}
